import 'package:flutter/material.dart';

void main() {
  // runApp 根组件
  runApp(MaterialApp(
      home: Scaffold(
    appBar: AppBar(
      title: const Text("我的第一个Flutter组件"),
    ),
    body: Column(
      children: const [
        Text('Hello 各位'),
        parents(),
      ],
    ),
  )));
}

class parents extends StatefulWidget {
  const parents({Key? key}) : super(key: key);

  @override
  _FatherChildState createState() => _FatherChildState();
}

class _FatherChildState extends State<parents> {
  int count = 10;

  callback(int value) {
    // 数据更新放在回调函数中
    setState(() {
      count = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
      const Text('父组件'),
      Text('$count'),
      // 父传子
      Child(
        callback: callback,
        count: count,
      )
    ]);
  }
}

class Child extends StatefulWidget {
  const Child({Key? key, this.callback, this.count}) : super(key: key);
  final Function(int)? callback;
  final int? count;

  @override
  _ChildState createState() => _ChildState();
}

class _ChildState extends State<Child> {
  @override
  Widget build(BuildContext context) {
    return Column(children: [
      const Text('子组件'),
      ElevatedButton(
        child: const Text('设置count的值，回调子传父'),
        onPressed: () {
          widget.callback!(100);
        },
      ),
      // 父传子
      Text('${widget.count}')
    ]);
  }
}
